var FG;
if (!FG)
    FG = {};

FG.plotTimeseries = function(itemlist, target, opts) {
    var firstdata = itemlist[0].data.data;
    var suggest_range = firstdata.suggest_range;
    var begdt = firstdata.begdt,
        interval = firstdata.interval;
    // TODO: smarter s/ms conversion
    if (interval < 100000) {
        begdt *= 1000;
        interval *= 1000;
    }
    
    var series = _.map(itemlist, function(item, i) {
        var values = (!!item.data.error) ? null : item.data.data.values
        return {
            name: item.tag,
            data: values
        };
    });
    
    target.highcharts('StockChart', {
        chart: {
            type: 'line'
            //zoomType: 'y',
        },
        exporting: {
            enabled: false
        },
        labels: {
            style: {
                fontSize: '12px'
            }
        },
        title: {
            text: itemlist[0].data.info.zh_varname + ' (' + itemlist[0].data.data.units + ')',
            floating: true,
            x: 70,
            y: 15
        },
        xAxis: {
            type: 'datetime',
            labels: {
                format: '{value: %Y-%m}',
                //rotation: 45,
                align: 'left'
            },
            events: {
                setExtremes: function(event) {
                    var button = event.rangeSelectorButton;
                    if (typeof button === 'undefined') {
                        return;
                    }
                    var dateFormatStr,
                        buttonType = button.type;
                    if (buttonType === 'day') {
                        dateFormatStr = '{value: %H:%M}';
                    }
                    else if (buttonType === 'week') {
                        dateFormatStr = '{value: %m-%d}';
                    }
                    else if (buttonType === 'month') {
                        dateFormatStr = '{value: %m-%d}';
                    }
                    else {
                        dateFormatStr = '{value: %Y-%m}';
                    }
                    var labels = {
                        'labels': {
                            'format': dateFormatStr
                        }
                    };
                    this.update(labels);
                }
            }
        },
        yAxis: {
            title: null,
            opposite: false,
            min: suggest_range[0],
            units: itemlist[0].data.data.units
        },
        navigator: {
            height: 20,
            margin: 3,
            xAxis: {
                dateTimeLabelFormats: {
                    month: '%b'
                }
            } /* ,
            maskFill: */
        },
        scrollbar: {
            height: 5,
            enabled: true
        },
        rangeSelector: {
            buttons: [{
                type: 'day',
                count: 1,
                text: '1天'
            }, {
                type: 'week',
                count: 1,
                text: '1周'
            }, {
                type: 'month',
                count: 1,
                text: '1月'
            }, {
                type: 'all',
                text: '1年'
            }],
            selected: 3,
            buttonTheme: {
                height: 12,
                style: {
                    fontSize: 12
                }
            },
            inputEnabled: false
        },
        colors: FG.getSetting('plot.colors', FG.DEFAULT_COLORS),
        series: series,
        //series: [{
        //    name: itemlist[0].data.info.zh_varname,
        //    data: itemlist[0].data.data.values
        //    //downsample: {
        //    //     threshold: 200
        //    //},
        //}],
        tooltip: {
            valueDecimals: 3,
            crosshairs: true,
            shared: false,
            useHTML: true,
            formatter: function() {
                var labelName = (itemlist.length === 1) ? itemlist[0].data.info.zh_varname : this.series.name;
                var xdate = Highcharts.dateFormat('%Y-%m-%d %H:%M', this.x);
                var format = '<table><tr><td><b>' + xdate +
                    ':' + '</b></td></tr>' +
                    '<tr><td style="text-align:left;color:' + this.series.color + '">' +
                    labelName + ':' + '</td>' +
                    '<td style="text-align: right">' +
                    this.y.toFixed(1) + itemlist[0].data.data.units + '</td></tr></table>';
                return format;
            }
        },
        legend: {
            enabled: false,
            title: {
                text: itemlist.commonTag
            }
        },
        plotOptions: {
            series: {
                pointStart: begdt,
                pointInterval: interval,
                lineWidth: 1,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                }
            }
        }
    })
    
    
};

FG.plotCategory = function(itemlist, target, opts) {
    var datatype = itemlist[0].data.info.type;
    var categories;
    if (datatype === 'monthlymean' || datatype === 'monthlystat') {
        categories = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
        var toolTipUnit = '月';
    } else if (datatype === 'diurnalmean' || datatype === 'diurnalstat') {
        categories = [
            '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',
            '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'
        ];
        var toolTipUnit = '点';
    }
    
    var series = _.map(itemlist, function(item){
        var values = (!!item.data.error) ? null : item.data.data.values;
        var res = {
            name: item.tag,
            data: values
        };
        return res
    });
    var stat_method = itemlist[0].data.data.stat_method;
    var chartType = 'line';
    if (!!stat_method && stat_method === 'sum') {
        chartType = 'column';
    }
    target.highcharts('Chart', {
        chart: {
            type: chartType
        },
        exporting: {
            enabled: false
        },
        title: {
            text: itemlist[0].data.info.zh_varname + ' (' + itemlist[0].data.data.units + ')'
        },
        xAxis: {
            //categories: itemlist[0].data.data.categories
            categories: categories
        },
        yAxis: {
            //title: {
            //    text: itemlist[0].data.info.zh_varname + ' (' + itemlist[0].data.data.units + ')',
            //},
            title: null,
            plotLines: [{
                width: 1,
                value: 0,
                color: '#808080'
            }]
        },
        colors: FG.getSetting('plot.colors', FG.DEFAULT_COLORS),
        legend: {
            enabled: false,
            title: {
                text: itemlist.commonTag
            }
        },
        tooltip: {
            borderWidth: 1,
            useHTML: true,
            formatter: function () {
                var labelName = (itemlist.length === 1) ? itemlist[0].data.info.zh_varname : this.point.series.name;
                var format = '<table><tr><td style="text-align:left"><b>' + this.x + toolTipUnit +
                    ':' + '</b></td></tr>' +
                    '<tr><td style="text-align:left;color:' + this.point.series.color + '">' +
                    labelName + ':' + '</td>' +
                    '<td style="text-align: right">' +
                    this.y.toFixed(1) + itemlist[0].data.data.units + '</td></tr></table>';
                return format;
            }
        },
        plotOptions: {
            series: {
                animation: true
            }
        },
        series: series
    })
};

FG.plotRose = function(itemlist, target, opts) {
    var toParse = itemlist[0];
    if (!!toParse.data.error) {
        // TODO: 显示错误
    }
    var series = [],
        sum = 0,
        finalUnits = '‰';
    for (var i=0; i<toParse.data.data.wsbins.length; i+=1) {
        sum += toParse.data.data.values[i].reduce(function(a, b) {return a+b}, 0);
    }
    
    for (var i=0; i<toParse.data.data.wsbins.length; i+=1) {
        var res = {};
        res.name = toParse.data.data.wsbins[i];
        res.data = _.map(toParse.data.data.values[i], function(a) {
            return a / sum * 1000;
        });
        series.push(res);
    }
    var units = itemlist[0].data.data.units;
    var labels;
    if (units !== '%' && units !== '‰') {
        labels = {
            enabled: true,
            items: [{
                html: '总和: '+sum.toFixed(1) + units,
                style: {
                    left: '350px',
                    top: '16px',
                    color: '#555'
                }
            }]
        }
    } else {
        labels = {enabled: false}
    }
    
    target.highcharts('Chart', {
        chart: {
            polar: true,
            type: 'column',
            margin: [15, 30, 0, 0]
        },
        exporting: {
            enabled: false
        },
        title: {
            text: itemlist[0].data.info.zh_varname + ' (' + finalUnits + ')',
            y: 10
        },
        colors: FG.getSetting('plot.rosecolors', FG.DEFAULT_ROSECOLORS),
        pane: {
            startAngle: 0,
            endAngle: 360,
            size: '80%'
        },
        legend: {
            align: 'right',
            layout: 'vertical',
            verticalAlign: 'bottom',
            reversed: true,
            floating: true,
            title: {
                style: {
                    fontWeight: 'bold'
                },
                text: '风速(m/s)'
            },
            x: 15,
            y: -5
        },
        tooltip: {
            useHTML: true,
            formatter: function() {
                var format = '<table><tr><td style="text-align:left"><b>' +
                    this.x + '°:</b></td></tr>' +
                    '<tr><td style="text-align:left;">' +
                    this.series.name + 'm/s:</td><td>' +
                    this.y.toFixed(1) + finalUnits + '</td></tr><tr><td style="text-align:left;">扇区总和:</td>' +
                    '<td>' + this.total.toFixed(1) + finalUnits + '</td></tr></table>';
                return format;
            }
        },
        xAxis: {
            categories: ['N/0', 'NNE/22.5', 'NE/45', 'ENE/67.5', 'E/90', 'ESE/112.5', 'SE/135', 'SSE/157.5',
                'S/180', 'SSW/202.5', 'SW/225', 'WSW/247.5', 'W/270', 'WNW/292.5', 'NW/315', 'NNW/337.5'],
            tickmarkPlacement: 'on',
            labels: {
                formatter: function(){
                    return this.value + '°';
                }
            }
        },
        yAxis: {
            min: 0,
            endOnTick: false,
            plotLines: [{
                color: '#808080',
                width: 1,
                value: 0
            }],
            units: itemlist[0].data.data.units,
            reversedStacks: false
        },
        plotOptions: {
            series: {
                stacking: 'normal',
                animation: true,
                pointPadding: 0,
                groupPadding: 0,
                pointPlacement: 'on'
            }
        },
        labels: labels,
        series: series
    })
};

FG.plotDist = function(itemlist, target, opts) {
    var categories;
    for (var i=0; i < itemlist.length; i+=1) {
        if (!itemlist[i].data.error) {
            categories = itemlist[i].data.data.wsbins;
            break;
        }
    }
    if (!categories) {
        //TODO: 处理错误
    }
    // var categories = itemlist[0].data.data.wsbins;
    var toolTipUnit = 'm/s';
    var series = _.map(itemlist, function(item){
        var res = {name: item.tag};
        if (!!item.data.error) {
            res.data = null
        } else {
            res.data = item.data.data.wsdist;
            if (categories.length > 25) {
                res.data = res.data.slice(0, 25);
            }
        }
        return res
    });
    if (categories.length > 25){
        categories = categories.slice(0, 25)
    }
    
    var plotColors = FG.getSetting('plot.colors', FG.DEFAULT_ROSECOLORS),
        plotColorN = plotColors.length;
    
    var labelItems = _.map(itemlist, function(item, i) {
        return {
            html: 'A: ' + item.data.data.weibull_a.toFixed(4) +
            ', K: ' + item.data.data.weibull_k.toFixed(4),
            style: {
                left: '280px',
                top: (8 + i*16).toString() + 'px',
                color: plotColors[i % plotColorN]
            }
        }
    });
    
    target.highcharts('Chart', {
        chart: {
            type: 'column'
        },
        exporting: {
            enabled: false
        },
        title: {
            text: itemlist[0].data.info.zh_varname + ' (' + itemlist[0].data.data.units + ')'
        },
        xAxis: {
            //categories: itemlist[0].data.data.categories
            categories: categories,
            min: -0.4
        },
        yAxis: {
            //title: {
            //    text: itemlist[0].data.info.zh_varname + ' (' + itemlist[0].data.data.units + ')',
            //},
            title: null,
            plotLines: [{
                width: 1,
                value: 0,
                color: '#808080'
            }]
        },
        labels: {
            //items: [{
            //    //html: 'A: ' + itemlist[0].data.data.weibull_a.toFixed(4) +
            //    //    ', K: ' + itemlist[0].data.data.weibull_k.toFixed(4),
            //    html: labelHtml,
            //    style: {
            //        left: '280px',
            //        top: '8px'
            //    }
            //}]
            items: labelItems
        },
        legend: {
            enabled: false,
            title: {
                text: itemlist.commonTag
            }
        },
        tooltip: {
            borderWidth: 1,
            useHTML: true,
            formatter: function () {
                var labelName = (itemlist.length === 1) ? itemlist[0].data.info.zh_varname : this.point.series.name;
                var format = '<table><tr><td style="text-align:left"><b>' + this.x + toolTipUnit +
                    ':' + '</b></td></tr>' +
                    '<tr><td style="text-align:left;color:' + this.point.series.color + '">' +
                    labelName + ':' + '</td>' +
                    '<td style="text-align: right">' +
                    this.y.toFixed(1) + itemlist[0].data.data.units + '</td></tr></table>';
                return format;
            }
        },
        plotOptions: {
            column: {
                animation: true,
                pointWidth: 12 / series.length,
                pointPlacement: -0.5,
                groupPadding: 0.1,
                pointPadding: 0.05
            }
        },
        series: series,
        colors: FG.getSetting('plot.colors', FG.DEFAULT_COLORS)
    })
};

FG.plotSummary = function(itemlist, target, opts) {
    // TODO: 也要处理有错误的unit.
    var $table,
        firstData = itemlist[0].data,
        tableName = !!firstData.info.zh_varname ? firstData.info.zh_varname : firstData.info.varname,
        subvns = firstData.info.sub_varnames,
        tableCorner = '',
        precision = 2;

    if (!!opts) {
        if (!!opts.tableName) {
            tableName = opts.tableName;
        }
        if (!!opts.corner) {
            tableCorner = opts.corner;
        }
        if (_.isNumber(opts.precision)) {
            precision = opts.precision;
        }
    }
    
    var heads = [];
    _.each(subvns, function(subvn) {
        var subdata = firstData.data[subvn];
        var name = !!subdata.zh_name ? subdata.zh_name : subdata.name;
        var units = !!subdata.units ? subdata.units : '';
        heads.push(
            '<th class="summary_head">' +
            name + '<span>' + units + '</span>' +
            '</th>')
    });
    
    var dataArr = [];
    _.each(itemlist, function(item, i) {
        var arrLine = [];
        var rawdata = item.data.data;
        _.each(subvns, function (subvn, j) {
            var subdata = rawdata[subvn];
            var content = '--';
            try {
                content = subdata.values.toFixed(precision);
            } catch (e) {
                content = String(subdata.values)
            }
            arrLine.push(content)
        });
        
        dataArr.push(arrLine);
    });
    
    var plotColors = FG.getSetting('plot.colors', FG.DEFAULT_COLORS),
        plotColorN = plotColors.length;
    
    if (!!opts && !!opts.vertical) {
        var labelHtmls = [];
        for (var i=0; i<itemlist.length; i++) {
            labelHtmls.push('<td class="summary_data labelcol"><i class="fa fa-circle" style="color:' + plotColors[i % plotColorN] + '"></i></td>');
        };
        var rows = [];
        for (var j=0; j<subvns.length; j++) {
            var rowHtmls = [heads[j]];
            for (var i=0; i<itemlist.length; i++) {
                rowHtmls.push('<td class="summary_data">' + dataArr[i][j] + '</td>')
            }
            rows.push('<tr>'+rowHtmls.join('')+'</tr>');
        }
        $table = $(
            '<table class="summary_table vertical_table">' +
            '<tr>' +
            '<th class="summary_head">' + tableCorner + '</th>' +
            labelHtmls.join('') +
            //'<th class="summary_head">年总辐射量(GJ/m²)</th>' +
            '</tr>' +
            rows.join('') +
            '</table>'
        );
    } else {
        var rows = [];
        for (var j=0; j<itemlist.length; j++) {
            var rowHtmls = ['<td class="summary_data labelcol"><i class="fa fa-circle" style="color:' + plotColors[j % plotColorN] + '"></i></td>'];
            for (var i=0; i<subvns.length; i++) {
                rowHtmls.push('<td class="summary_data">' + dataArr[j][i] + '</td>')
            }
            rows.push('<tr>'+rowHtmls.join('')+'</tr>');
        }
        $table = $(
            '<table class="summary_table">' +
            '<tr>' +
            '<th class="summary_head">' + tableCorner + '</th>' +
            heads.join('') +
            //'<th class="summary_head">年总辐射量(GJ/m²)</th>' +
            '</tr>' +
            rows.join('') +
            '</table>'
        )
    }
    
    target.append('<div class="head">' + tableName + '</div>');
    target.append($table);
};

